import { Injectable } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { UserService } from '../user/user.service';

export type User = {
  id: number;
  username: string;
  password: string;
  roles: string[];
  active?: boolean;
};

@Injectable()
export class AuthService {
  private readonly users: User[] = [
    // 应急情况下的用户（超管） // TODO 该数据应该从配置中获取，以便紧急情况下重置密码
    // {
    //   id: 1,
    //   username: 'admin',
    //   password: 'admin123#Nest', 
    //   roles: ['super'], // 超级管理员角色
    // },
  ];

  constructor(
    private jwtService: JwtService,
    private userService: UserService,
  ) {}

  async validateUser(username: string, password: string): Promise<any> {
    // 首先检查硬编码的用户（紧急用户）
    let user = this.users.find(
      (u) => u.username === username && u.password === password,
    );
    
    // 如果没找到，再检查数据库中的用户
    if (!user) {
      const dbUser = await this.userService.findByUsername(username);
      if (dbUser && dbUser.password === password) {
        // 获取用户的角色
        const roles = await this.userService.getUserRoles(username);
        user = {
          id: dbUser.id,
          username: dbUser.username,
          password: dbUser.password,
          roles: roles,
        };
      }
    }
    
    if (user) {
      // 移除密码字段
      const { password, ...result } = user;
      return result;
    }
    return null;
  }

  async login(user: any) {
    // 构建包含所有用户属性的payload
    const { password, ...payload } = { ...user, sub: user.id };
    return {
      access_token: this.jwtService.sign(payload),
    };
  }
}